<?php
/**
 * Created by PhpStorm.
 * User: divya
 * Date: 2018/8/2
 * Time: 上午11:35
 */

namespace app\api\controller\v1;


use app\api\validate\AddressNew;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\TokenExption;
use app\lib\exception\UserException;
use think\Controller;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;

class Address extends Controller
{
    //每当执行creatOrUpdate方法时总是先执行checkPrimaryScope方法
    protected $beforeActionList = [
        'checkPrimaryScope'=>['only'=>'creatOrUpdate']
    ];
    public function creatOrUpdate(){
        $validate =  new AddressNew();
        $validate->goCheck();
        // 根据Token来获取uid
        // 根据uid来查找用户，判断用户是否存在
        // 获取用户从客户端提交来的信息
        // 根据用户地址信息是否存在，从而判断是添加地址还是更新地址
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if (!$user){
            throw new UserException();
        }
        $dateArray = $validate->getDataByRule(input('post.'));
//        echo json_encode($dateArray);
        $userAddress = $user ->address();
        if (!$userAddress){
            $user->address()->save($dateArray);
        }else{
            $user->address->save($dateArray);
        }
        return json(new SuccessMessage(),201);
    }

}